import json
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts, TitleOpts, LabelOpts

# 读取数据文件
f = open("D:\\file\\疫情.txt", "r", encoding="utf-8")
data = f.read()
# 关闭文件
f.close()
# 取到各省数据
# 将字符串json转换为字典
data_dict = json.loads(data)
# 从字典中取出各个省的数据列表
province_data_list = data_dict["areaTree"][0]["children"]
# 组装到每个省份和确诊人数为元组, 并各个省的数据都封装到列表中
data_list = []        # 绘图需要用的数据列表
for province_data in province_data_list:
    province_name = province_data["name"]                   # 省份名称
    if province_name == "北京" or province_name == "上海" or province_name == "天津" or province_name == "重庆":
        province_name = province_name + "市"
    elif province_name == "香港" or province_name == "澳门":
        province_name = province_name + "特别行政区"
    elif "自治区" not in province_name:
        province_name = province_name + "省"
    province_confirm = province_data["total"]["confirm"]    # 确证人数
    data_list.append((province_name, province_confirm))
print(data_list)
# 创建地图对象
map = Map()
# 添加数据
map.add("各省确诊人数", data_list, "china", label_opts=LabelOpts(is_show=False))
# 设置全局配置,定制分段视觉映射
map.set_global_opts(
    title_opts=TitleOpts(title="全国疫情地图", pos_left="center", pos_bottom="1%"),
    # 视觉映射配置
    visualmap_opts=VisualMapOpts(
        is_show=True,       # 是否显示
        is_piecewise=True,  # 是否分段
        pieces=[
            {"min": 1, "max": 99, "label": "1~99人", "color": "#CCFFFF"},
            {"min": 100, "max": 999, "label": "100~999人", "color": "#FFFF99"},
            {"min": 1000, "max": 4999, "label": "1000~4999人", "color": "#FF9966"},
            {"min": 5000, "max": 9999, "label": "5000~9999人", "color": "#FF6666"},
            {"min": 10000, "max": 99999, "label": "10000-99999人", "color": "#CC3333"},
            {"min": 100000, "label": "100000~人", "color": "#990033"},
        ]
    ),

)

# 绘图
map.render("全国疫情地图.html")
